<?php
namespace Api
{
/**
 * Ajax event class for ajax listeners
 * 
 * To register new listener you must add
 * it name in global confing file to 'EventListener'
 * array in root.
 *   
 * @author Lukasz Torba
 */
    class AjaxEvent
    {
        const   EVENT_NAME = 'event';   // event address ( param name )                              
        const   EVENT_NAMESPACE = 'Event';
        const   EVENT_PREFIX = '__event__';
        
        /**
         * Reciving and preparing event data
         * @return reference to event listener
         */
        static public function &ParseEventData($privilages)
        {            
            \Api\Session::SessionRenew();
            \Api\Config::Renew($privilages);        
                            
                
            $config = \Api\Config::Load(\Api\Config::$param[\Api\ObjectLoader::C_MODULE]);
            if(!array_key_exists('EventListenerDirectory',$config))
            {
                throw new \Exception('EVENT: Mising listener in your global config.');
            }
            
            if(!array_key_exists(self::EVENT_NAME, $_GET) || $_GET[self::EVENT_NAME]==''){            
                throw new \Exception('EVENT: MISSING EVENT NAME');
            }       
            
            $event = preg_replace('/-/','',$_GET[self::EVENT_NAME]);
                        
            
            // First, check does any of registered listener have
            // search event function            
            foreach($config['EventListenerDirectory'] as $k => $v)
            {                        
                $event_class = $v.'\\'.preg_replace('/_/','',$event);
                if(is_file(preg_replace('/\\\/','/',BASE_PATH.'\\'.$event_class).'.php') !== false)
                {                     
                    // If it has, then call event listener execute                    
                    $listener =  new $event_class; // With class event name                   
                    $listener->__execute($v, self::EVENT_PREFIX.$event, $_POST, $config);
                    return $listener;
                }
            }
            
            throw new \Exception('EVNET: Unknown event '.$event);
        }        
    }
}
?>